package com.isoft.service.impl;

import com.isoft.entity.BaseCfueEntity;
import com.isoft.mapper.BaseCfueMapper;
import com.isoft.service.BaseCfueService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class BaseCfueServiceImpl implements BaseCfueService {
    private static final Logger logger = LoggerFactory.getLogger(BaseCfueServiceImpl.class);

    @Autowired
    private BaseCfueMapper baseCfueMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing BASE-CFUE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(BaseCfueEntity entity) {
        processAircraftData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            BaseCfueEntity entity = xmlParserUtil.parseXml(xmlContent, BaseCfueEntity.class);

            if (entity == null || entity.getCrft() == null) {
                throw new IllegalArgumentException("Invalid BASE-CFUE XML structure");
            }

            processAircraftData(entity);

            return "Aircraft data processed successfully. Aircraft code: " + entity.getCrft().getCode();
        } catch (Exception e) {
            logger.error("BASE-CFUE XML processing failed", e);
            throw new RuntimeException("Failed to process BASE-CFUE XML: " + e.getMessage());
        }
    }

    private void processAircraftData(BaseCfueEntity entity) {
        try {
            // 1. 验证飞机数据
            if (entity.getCrft() == null) {
                throw new IllegalArgumentException("Aircraft data is null");
            }

            String aircraftType = entity.getCrft().getAircraftType();
            String aircraftNumber = entity.getCrft().getCode();

            if (aircraftType == null || aircraftType.trim().isEmpty()) {
                throw new IllegalArgumentException("Aircraft type is required");
            }

            if (aircraftNumber == null || aircraftNumber.trim().isEmpty()) {
                throw new IllegalArgumentException("Aircraft number is required");
            }

            // 2. 插入元数据
            baseCfueMapper.insertMeta(entity);
            logger.debug("Inserted meta data for aircraft: {}", aircraftNumber);

            // 3. 获取下一个可用的航班ID
            Long nextFlightId = baseCfueMapper.getNextFlightId();
            logger.debug("Next available flight ID: {}", nextFlightId);

            // 4. 插入虚拟航班记录
            baseCfueMapper.insertDummyFlight(nextFlightId);
            logger.debug("Inserted dummy flight with ID: {}", nextFlightId);

            // 5. 插入飞机记录并关联虚拟航班
            baseCfueMapper.insertAircraftWithFlight(
                    nextFlightId,
                    aircraftType,
                    aircraftNumber
            );
            logger.info("Successfully inserted aircraft record. Type: {}, Number: {}, Flight ID: {}",
                    aircraftType, aircraftNumber, nextFlightId);

            // 6. 新增：插入航班异常信息到FLIGHT_IRREGULARITY表
            try {
                baseCfueMapper.insertIrregularity(nextFlightId);
                logger.debug("插入航班异常信息成功，航班ID: {}", nextFlightId);
            } catch (Exception e) {
                logger.warn("插入航班异常信息失败，航班ID: {}", nextFlightId, e);
            }

        } catch (Exception e) {
            logger.error("Failed to process aircraft data. Aircraft: {}",
                    entity.getCrft() != null ? entity.getCrft().getCode() : "null", e);
            throw new RuntimeException("Aircraft data processing failed: " + e.getMessage(), e);
        }
    }
}